package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.ArrayUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private IScheduleClient scheduleClient;

    @Override
    public void autoScanWmNews(Long newsId) throws Exception {
        //0,判断是否为空
        if (newsId == null) {
            log.warn("文章id为空");
            return;
        }
        //1.根据newsId查询WmNews信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }

        //2.提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        //3.提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> image = getImage(images, content);
        //3.1通过ocr提取图片中的文字
        String textFromOcr=ocrCheck(image);
        text=text+"_"+textFromOcr;
        //3.2调用DFA算法进行自建敏感词处理
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            //dfa检查未通过
            updateWmNews(2,"dfa审核未通过",null,newsId.intValue());
            return;
        }
        //4,调用文字审核接口
        //4.1审核失败->wmNews修改方法
        //4.2审核不确定->wmNews修改方法
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(textScan, null, newsId.intValue());
        if(!textScanResult){
            log.warn("文字审核失败");
            return;
        }
        //5.调用图片审核接口
        //5.1审核失败->wmNews修改方法
        //5.2审核不确定->wmNews修改方法
        Map imageScan = greenImageScan.imageScan(image);
        Boolean imageScanResult = checkResult(imageScan,null , newsId.intValue());
        if(!imageScanResult){
            log.warn("图片审核失败");
            return;
        }
        //6.远程调用ArticleClient保存文章
        //6.1判断响应结果是不是200
        ArticleDto dto=wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        if(responseResult==null||responseResult.getCode()!=200){
            log.warn("文章保存失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();
        //7.将articleid回写到wmNews表中
        updateWmNews(9,"审核通过",articleId,newsId.intValue());

    }

    private String ocrCheck(List<byte[]> image) throws TesseractException, IOException {
        if (CollectionUtils.isEmpty(image)) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (byte[] item : image) {
            //调用ocr工具类,提取里面的文字内容
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(item);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);
            //将文字内容组成一个字符串,返回
            builder.append("_").append(text);
        }
        return builder.toString();
    }

    private Boolean dfaCheck(String text){
        if (StringUtils.isBlank(text)) {
            return true;
        }
        //1.调用敏感词Mapper,查询所有敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(wmSensitives)){
            return true;
        }

        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }
        //2.DFA初始化
        SensitiveWordUtil.initMap(words);
        //3.DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);
        //4.判断结果
        return CollectionUtils.isEmpty(result);
    }

    private String getText(String title, String content) {
        if (StringUtils.isEmpty(content)) {
            return title;
        }
        //1.提取content内容,json字符串转成集合
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            log.warn("content内容为空");
            return title;
        }
        //2.遍历
        StringBuilder builder = new StringBuilder();
        for (Map item : maps) {
            if (CollectionUtils.isEmpty(item)) {
                continue;
            }
            Object type = item.get("type");
            if ("text".equals(type)) {
                String value = (String) item.get("value");
                //3.StringBuilder组合
                builder.append(value);
            }
        }
        //4.组合title并返回
        builder.append("_").append(title);
        return builder.toString();
    }

    private List<byte[]> getImage(String images, String content) {
        //0.生成大集合
        ArrayList<String> finalList = new ArrayList<>();
        //1.判断images是否为空
        if (StringUtils.isNotBlank(images)) {
            //1.1提取images里的图片连接(,)split()
            String[] split = StringUtils.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                List<String> list = Arrays.asList(split);
                //加入到大集合
                finalList.addAll(list);
            }
        }
        //2.判断content是否为空
        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map item : maps) {
                    if (CollectionUtils.isEmpty(item)) {
                        continue;
                    }
                    Object type = item.get("type");
                    if ("image".equals(type)) {
                        String value = (String) item.get("value");
                        finalList.add(value);
                    }
                }
            }
        }
        //3.遍历finalList转成数组
        ArrayList<byte[]> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(finalList)) {
            for (String url : finalList) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                byte[] bytes = minIoTemplate.downLoadFile(url);
                result.add(bytes);
            }

        }
        //4,返回集合
        return result;
    }

    private Boolean checkResult(Map result,Long articleId,Integer newsId){
        if (CollectionUtils.isEmpty(result)) {
            log.warn("审核结果为空");
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        if("pass".equals(suggestion)){
            return true;
        }else if("block".equals(suggestion)){
            //更新wmNews状态
            //不通过
            updateWmNews(2,"未通过",articleId,newsId);
            return false;
        }else if("review".equals(suggestion)){
            //更新wmNews状态
            //不确定
            updateWmNews(3,"人工审核",articleId,newsId);
            return false;
        }
        return true;
    }

    private ArticleDto wmNews2ArticleDto(WmNews wmNews){
        if (wmNews==null) {
            return null;
        }
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setLayout(wmNews.getType());
        //查询渠道的名称
        Integer channelId = wmNews.getChannelId();
        if (channelId!=null) {
            WmChannel channel = wmChannelMapper.selectById(channelId);
            if(channel!=null){
                articleDto.setAuthorName(channel.getName());
            }
        }
        //查询作者的名称
        Integer userId = wmNews.getUserId();
        if(userId!=null){
            WmUser wmUser = wmUserMapper.selectById(userId);
            if(wmUser!=null){
                articleDto.setAuthorId(userId.longValue());
                articleDto.setAuthorName(wmUser.getName());
            }
        }
        return articleDto;
    }

    private Boolean updateWmNews(Integer status,String reason,Long articleId,Integer newsId){
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        if(articleId!=null){
            wmNews.setArticleId(articleId);
        }
        int result = wmNewsMapper.updateById(wmNews);
        if(result<1){
            return false;
        }
        return true;
    }

    @Scheduled(fixedRate = 1000)
    public void getTask( ){
        ResponseResult poll = scheduleClient.poll();
        if(poll==null||poll.getCode()!=200){
            log.warn("消费失败");
            return;
        }
        String date = poll.getData().toString();
        if (StringUtils.isEmpty(date)) {
            log.warn("没有可消费的任务");
            return;
        }
        Task task = JSON.parseObject(date, Task.class);
        if (task==null) {
            log.warn("没有可消费的任务");
            return;
        }
        WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(),WmNews.class);
        if (wmNews==null) {
            log.warn("参数缺失");
            return;
        }
        try {
            autoScanWmNews(wmNews.getId().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

